package com.zwb.service.config;

import com.zwb.service.common.MailConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author 头发又黑又长
 * @Date 2022/9/11 12:03
 * @email zwb15083976291@163.com
 */
@Slf4j
@Configuration
public class RabbitConfig {

    @Autowired(required = false)
    private CachingConnectionFactory cachingConnectionFactory;

    @Bean
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(cachingConnectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

    @Bean
    public CustomExchange delayExchange() {
        HashMap<String, Object> arguments = new HashMap<>();
        // 声明延迟类型
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(MailConstants.DELAY_EXCHANGE,
                "x-delayed-message", true, false, arguments);
    }

    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable(MailConstants.DELAY_QUEUE).build();
    }

    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(MailConstants.DELAY_EMAIL_ROUTING_KEY).noargs();
    }
}
